package com.ijiuchuang.jc_localization.model.tools;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;

import com.ijiuchuang.jc_localization.ble.BleUtil;
import com.ijiuchuang.jc_localization.contract.tools.ToolsConnectionContract;
import com.ijiuchuang.jc_localization.tools.utils.HexUtil;
import com.ijiuchuang.jc_localization.tools.utils.Log;

import java.util.List;
import java.util.UUID;

/**
 * Created by Veev on 2016/7/21
 *
 * @link 384506557@qq.com
 */
public class ToolsConnectionModel implements ToolsConnectionContract.Model {

    private static BluetoothGatt mBluetoothGatt;
    public final static UUID UUID_CHZU_SERIAL_PORT_CHAR =
            UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_CHZU_SERIAL_PORT_CHAR_READ =
            UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_CHZU_SERIAL_PORT_SERVICE =
            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");

    private BluetoothGattCharacteristic mSerialDataChar = null;
    private BluetoothGattCharacteristic mWriteDataChar = null;

    /**
     * GATT 回调
     */
    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        //状态改变时调用
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTING:
                    // 连接中
                    Log.i("连接中");
                    break;
                case BluetoothProfile.STATE_CONNECTED:
                    // 已连接
                    Log.i("已连接 " + gatt.getDevice().getAddress());
                    //mBluetoothGatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    // 已断开
                    Log.i("已断开");
                    break;
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> gattServices = mBluetoothGatt.getServices();
                for (BluetoothGattService gattService : gattServices) {
                    //Log.i("222 uuid:"+gattService.getUuid()+",type:"+gattService.getType()+",InstanceId:"+gattService.getInstanceId());
                    //Log.i("333 Characteristics:"+gattService.getCharacteristics());
                    for (BluetoothGattCharacteristic bbbb : gattService.getCharacteristics()){
                        //Log.i("444 - uuid:" + bbbb.getUuid() + ", Properties:" + bbbb.getProperties());
                    }
                    if(UUID_CHZU_SERIAL_PORT_SERVICE.equals(gattService.getUuid()))
                    {
                        // 只需要发送数据
                        mSerialDataChar = gattService.getCharacteristic(UUID_CHZU_SERIAL_PORT_CHAR);
                        mWriteDataChar = gattService.getCharacteristic(UUID_CHZU_SERIAL_PORT_CHAR_READ);

                        writeCharacteristic(new byte[]{1});
                        if (null != mBluetoothGatt && null != BleUtil.getBluetoothAdapter()) {
                            setCharacteristicNotification(mSerialDataChar, true);
                            //mBluetoothGatt.readCharacteristic(mSerialDataChar);
                            Log.i("000");
                        }
                    }
                }
            } else {
                Log.i("onServicesDiscovered received: " + status);
            }
        }

        // 读到数据时调用
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.i("有数据来了 Read");
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Log.i("有数据来了 Changed - " + HexUtil.encodeHexStr(characteristic.getValue()));
        }

        // 发送数据
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.i("发送数据: " + status);
        }
    };

    @Override
    public void connect(Context context, BluetoothDevice device) {
        if (BleUtil.getBluetoothAdapter() == null || device == null) {
            return ;
        }
        mBluetoothGatt = device.connectGatt(context, false, gattCallback);
    }

    /**
     * 写数据
     * @param data
     */
    private void writeCharacteristic(byte[] data) {
        if (mBluetoothGatt != null && BleUtil.getBluetoothAdapter() != null) {
            mWriteDataChar.setValue(data);
            mBluetoothGatt.writeCharacteristic(mWriteDataChar);
        }
    }

    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (null == BleUtil.getBluetoothAdapter() || null == mBluetoothGatt) {
            Log.w("BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        List<BluetoothGattDescriptor> descriptors=characteristic.getDescriptors();
        for(BluetoothGattDescriptor dp:descriptors) {
            dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(dp);
        }
    }
}
